import { Button, Form, Modal } from "@/components/base";
import type { IOption } from "../..";
import React from "react";
import { makeAutoObservable, runInAction } from "mobx";
import { useObserver } from "mobx-react-lite";
import { useLoading } from "@shared/utils/hooks";

export class MainController {
    /**
     * 弹窗是否打开
     */
    open: boolean = true;

    /**
     * 弹窗数据
     */
    data?: any;

    constructor() { makeAutoObservable(this) }
}

export const Main = (props: IOption & { afterClose?: () => void, controller: MainController }) => {

    const { controller } = props;
    const { data } = controller;
    const [form] = Form.useForm(props.form);
    const { run, loading } = useLoading()

    const onOk = React.useCallback(async () => {
        run(async () => {
            const values = await form.validateFields();
            await props.onSubmit?.(values, data);
            runInAction(() => {
                controller.open = false;
            })
        })
    }, [controller, data, form, props, run]);

    const onCancel = React.useCallback(() => {
        runInAction(() => {
            controller.open = false;
        })
    }, [controller]);

    return useObserver(() => (
        <Modal
            title={props?.title}
            open={controller?.open}
            onOk={onOk}
            onCancel={onCancel}
            okText={props?.okText}
            cancelText={props?.cancelText}
            afterClose={props?.afterClose}
            footer={[
                <Button loading={loading} onClick={onCancel} >{props?.cancelText || '取消'}</Button>,
                <Button loading={loading} onClick={onOk} type='primary' >{props?.okText || '确定'}</Button>,
            ]}
        >
            <Form
                form={form}
                labelCol={props?.labelCol}
                initialValues={props?.initialValues}
                layout={props?.layout || 'vertical'}
            >
                {props?.children}
            </Form>
        </Modal>
    ))
}